package PrjRPC

import (
	"dgo/goutils/utils"
	"errors"
)

type RPCCmdRec struct {
	id       string
	sendfunc func(data []byte) error
	tagdata  interface{}
}

type rp_hand_func func(sender *RPCCmdRec, data interface{})

type RPC struct {
	cmd_rec_map  utils.GSyncMapGroup
	handfunc_map utils.GSyncMapGroup
	SendFunc     func(id string, method_Id string, data interface{})
}

func NewRPC() *RPC {
	val := &RPC{}
	return val
}

func (this *RPC) RegsterRPCHandFunc(method_Id string, hand_func rp_hand_func) {
	this.handfunc_map.Set(method_Id, hand_func)
}

func (this *RPC) Invoke_rp_func(sender *RPCCmdRec, method_Id string, data interface{}) {
	fv := this.handfunc_map.Get(method_Id, nil)
	if fv == nil {
		if sender.sendfunc != nil {
			sender.sendfunc([]byte("404 not found!"))
		}
	} else {
		fv1 := fv.(rp_hand_func)
		fv1(sender, data)
	}
}

func (this *RPC) CheckGetCmdRec(id string) *RPCCmdRec {
	return this.cmd_rec_map.LoadOrStoreFunc(id, func() interface{} {
		rval := &RPCCmdRec{
			id: id,
		}
		rval.NullSendFunc()
		return rval
	}, nil).(*RPCCmdRec)
}

func (this *RPCCmdRec) SendFuncAssign(sendfunc func(data []byte) error) {
	this.sendfunc = sendfunc
}

func (this *RPCCmdRec) NullSendFunc() {
	this.sendfunc = func(data []byte) error {
		return errors.New("null")
	}
}
